// 得到游戏画布和画笔
var gameCarvas = document.getElementById('gameCanvas');
var gameContext = gameCarvas.getContext("2d");

// 得到显示下一个方块的画布和画笔
var nextCarvas = document.getElementById('nextCanvas');
var nextContext = nextCarvas.getContext('2d');

// 定义方格大小
var blockSize = window.innerWidth * 0.6 / 10;
// 
var timer;
var score = 0;//分数
gameCarvas.width = blockSize * 10 + 2;
gameCarvas.height = blockSize * 20 + 2;
var gameW = gameCarvas.width;
var gameH = gameCarvas.height;
nextCarvas.width = blockSize * 4;
nextCarvas.height = blockSize * 2;
// 存储所有方块
var list = [];
// 定义俄罗斯方块的形状，二维数组表示
var layouts = [
    [1, 1, 1, 1],
    [[1, 1], [1, 1]],
    [[0, 1, 0], [1, 1, 1]],
    [[1, 1, 0], [0, 1, 1]],
    [[0, 1, 1], [1, 1, 0]],
    [[1, 0, 0], [1, 1, 1]],
    [[0, 0, 1], [1, 1, 1]],
];
// 画网格
drawLine();
// 定义一个俄罗斯方块
var shape;
// next display block
var nextShape;
// 创建俄罗斯方块，并画在画布上
shape = new Shape();
shape.img.onload = function () {
    shape.drawShape();
}
nextShape = new NextShape();
nextShape.img.onload = function () {
    nextShape.updateFrame();
    nextShape.drawNextShape();
}
// 得到5个图片按钮
var imgs = document.querySelectorAll('img');
for (let i = 0; i < imgs.length; i++) {

    let img = imgs[i];
    // 给图片增加属性
    // 暂停 0，变形 1，加速 2 ，向左 3，向右 4， 
    img.index = i;
    img.onclick = function () {
        keyAndDown(this.index);
    }

}
var isStart = true;//表示正在下落
// 处理用户按钮处理的函数


// 方块的下落
// move();
timer = setInterval("move()", 100);

function keyAndDown(key) {
    let btn = document.querySelector('img');
    switch (key) {

        case 0://stop
            if (isStart) {
                // 执行状态 变成暂停状态
                clearInterval(timer);
                btn.src = 'img/bofang.png';//该图标表示要播放
                isStart = false;
            } else {
                isStart = true;
                btn.src = 'img/zanting.png';//该图标表示要暂停
                timer = setInterval("move()", 100);

            }

            break;
        default:
            if (isStart) {
                switch (key) {
                    case 1://变形 2,3=>3,2 

                        //转置。。。
                        let lay = [];
                        for (let j = 0; j < shape.layout[0].length; j++) {
                            lay[j] = [];
                            for (let i = 0; i < shape.layout.length; i++) {
                                lay[j][i] = shape.layout[shape.layout.length - i - 1][j];//新的下标
                            }

                        }
                        // 变形后的坐标
                        let offSetX = shape.currentX + lay[0].length;
                        let offSetY = shape.currentY + lay.length;
                        // 记录方块本来的坐标
                        let xZuobiao = shape.currentX;
                        let yZuobiao = shape.currentY;
                        if (offSetX > 10) {
                            xZuobiao = 10 - lay[0].length;

                        }
                        if (offSetY > 20) {
                            yZuobiao = 20 - lay.length;
                        }
                        // 检测变形后的方块是否和其他方块有重叠
                        for (let i = 0; i < lay.length; i++) {
                            for (let j = 0; j < lay[0].length; j++) {
                                if (lay[i][j] > 0 && list[yZuobiao + i][xZuobiao + j] > 0) {
                                    return;
                                }
                            }

                        }
                        shape.currentX = offSetX;
                        shape.currentY = offSetY;
                        shape.layout = lay;
                        break;
                    case 2://加速
                        if (isMove(0, 2)) {
                            shape.currentY += 2;
                        }
                        break;
                    case 3://向左
                        if (isMove(-1, 0)) {
                            shape.currentX--;
                        }
                        break;
                    default://向右
                        if (isMove(1, 0)) {
                            shape.currentX++;
                        }
                        break;
                }
            }
            break;
    }
}

function drawLine() {
    // 横线
    // 21根线
    for (let i = 0; i < 21; i++) {
        gameContext.beginPath();
        gameContext.strokeStyle = "white";
        gameContext.lineWidth = 2;

        // 起点
        gameContext.moveTo(0.5, blockSize * i + 0.5);
        // 终点
        gameContext.lineTo(blockSize * 10 + 0.5, blockSize * i + 0.5);
        // 开始画
        gameContext.stroke();
        // 结束画
        gameContext.closePath();
    }
    // 纵线 11根
    for (let j = 0; j < 11; j++) {
        gameContext.beginPath();
        gameContext.strokeStyle = "white";
        gameContext.lineWidth = 2;

        // begin
        gameContext.moveTo(blockSize * j + 0.5, 0.5);
        // end
        gameContext.lineTo(blockSize * j + 0.5, blockSize * 20 + 0.5);

        // begin to draw
        gameContext.stroke();
        // close
        gameContext.closePath();
    }
}
// 定义俄罗斯方块
function Shape() {
    // 初始位置
    this.currentX = 3;//下标
    this.currentY = 0;

    this.img = getImg();
    // 随机的取方块的颜色

    this.color = Math.floor(Math.random() * 7);//0 --- 6

    // shape
    this.layout = layouts[Math.floor(Math.random() * 7)];

    // draw block
    this.drawShape = function () {
        for (let i = 0; i < this.layout.length; i++) {
            for (let j = 0; j < this.layout[i].length; j++) {
                if (this.layout[i][j] > 0) {
                    gameContext.drawImage(this.img, this.color * 20, 0, 20, 20, (this.currentX + j) * blockSize, (this.currentY + i) * blockSize, blockSize, blockSize);
                }
            }
        }
    }
    this.updateFrame = function () {
        this.currentY++;
    }
}
function getImg() {
    let img = new Image();
    img.src = './img/blocks1.png';
    return img;
}
// 创建列表！
createList();
// 程序的入口 
function move() {
    // 改变方块的纵坐标
    if (isMove(0, 1)) {
        shape.currentY++;
    } else {
        // 新的方块要下落,下一个俄罗斯方块的属性赋值给俄罗斯方块。
        pushShapeToList();
        clearList();//只要存了方块，才有可能满一行；
        shape.currentX = 3;
        shape.currentY = 0;
        shape.color = nextShape.color;
        shape.layout = nextShape.layout;
        // 判断游戏是否应该结束，有重叠的
        for (let i = 0; i < shape.layout.length; i++) {
            for (let j = 0; j < shape.layout[0].length; j++) {
                if (shape.layout[i][j] > 0 && list[shape.currentY + i][shape.currentX + j]) {
                    window.location.reload();
                }
            }
        }



        // 更新下一个 方块的值
        nextShape.updateFrame();
        nextContext.clearRect(0, 0, nextCarvas.width, nextCarvas.height);
        nextShape.drawNextShape();

    }

    // 更新画布
    updateGameCavas();

    // console.log(111);
}
function updateGameCavas() {
    // 清空整个画布
    gameContext.clearRect(0, 0, gameW, gameH);
    drawLine();
    shape.drawShape();
    // 画不在下落的方块
    drawList();
}
// 传入移动以步数。 y
function isMove(x, y) {
    let nextX = shape.currentX + x;
    let nextY = shape.currentY + y;
    if (nextY > (20 - shape.layout.length)) {
        return false;
    }
    if (nextX < 0 || nextX > (10 - shape.layout[0].length)) {
        return false;
    }
    // 判断正在下落的是否有重叠
    for (let i = 0; i < shape.layout.length; i++) {
        for (let j = 0; j < shape.layout[i].length; j++) {
            if (shape.layout[i][j] > 0 && list[nextY + i][nextX + j] > 0) {
                return false;
            }
        }
    }
    return true;
    // return (shape.currentY + y) <= (20 - shape.layout.length) ? true : false;
}

// 定义下一个方块
function NextShape() {
    this.img = getImg();


    this.updateFrame = function () {
        // 随机的取方块的颜色

        this.color = Math.floor(Math.random() * 7);//0 --- 6

        // shape
        this.layout = layouts[Math.floor(Math.random() * 7)];
    }
    // draw block
    this.drawNextShape = function () {
        for (let i = 0; i < this.layout.length; i++) {
            for (let j = 0; j < this.layout[i].length; j++) {
                if (this.layout[i][j] > 0) {
                    nextContext.drawImage(this.img, this.color * 20, 0, 20, 20, j * blockSize, i * blockSize, blockSize, blockSize);
                }
            }
        }
    }
}

// 存储不再下落的数据结构
function createList() {
    for (let i = 0; i < 20; i++) {
        list[i] = [];
        for (let j = 0; j < 10; j++) {
            list[i][j] = 0;
        }
    }
}
// 存储不在下落的数据
function pushShapeToList() {
    // 得到形状
    for (let i = 0; i < shape.layout.length; i++) {
        for (let j = 0; j < shape.layout[i].length; j++) {
            if (shape.layout[i][j] > 0) {
                console.log(shape.layout);
                list[shape.currentY + i][shape.currentX + j] = shape.color + 1;//0 -- 6 ==>1---7 o disapper
                console.log("color is" + list[shape.currentY + i][shape.currentX + j]);
            }
        }
    }
}
// 把不在落在上面的的画上画布
function drawList() {
    let img = getImg();
    // console.log('draw list');
    for (let i = 0; i < list.length; i++) {
        for (let j = 0; j < list[i].length; j++) {
            if (list[i][j] > 0) {
                // console.log(list[i][j]);
                gameContext.drawImage(img, (list[i][j] - 1) * 20, 0, 20, 20, j * blockSize, i * blockSize, blockSize, blockSize);
            }
        }
    }
}
// 清除一行
function clearList() {
    // list中只要有一行大于0，那么这一行就可以消除
    for (let i = (list.length - 1); i > 0; i--) {
        // 都大于0 ，可以消除
        let flag = true;
        for (let j = 0; j < list[0].length; j++) {
            // console.log(i+" "+j);
            if (list[i][j] == 0) {
                flag = false;
                break;
            }
        }
        // 判断flag的值
        if (flag) {
            // 消除一行
            for (let k = i; k > 0; k--) {
                for (let l = 0; l < list[0].length; l++) {
                    list[k][l] = list[k - 1][l];//整体下移
                }
            }
            score += 10;
            document.getElementById('score').innerHTML = '得分为：' + score;
            // 消除之后 i++，消除最后一行
            i++;
        }

    }
}
